<template>
  <view class="container">
    <!-- 状态栏 -->
    <view class="status-bar">
      <view class="flex items-center">
        <uni-icons type="wifi-filled" size="28" color="#333333" class="mr-2"></uni-icons>
        <uni-icons type="battery" size="28" color="#333333"></uni-icons>
      </view>
    </view>

    <!-- 返回按钮 -->
    <view class="back-button" @tap="goBack">
      <uni-icons type="left" size="24" color="#FFFFFF"></uni-icons>
    </view>

    <!-- 菜品图片 -->
    <image :src="dish.image" mode="aspectFill" class="dish-image"></image>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 菜品基本信息卡片 -->
      <view class="info-card">
        <!-- 加减号按钮 -->
        <view class="quantity-btn">
          <uni-icons v-if="quantity > 0" type="minus-filled" size="24" color="#3db87f" @click="decreaseQuantity"></uni-icons>
          <text v-if="quantity > 0" class="quantity-text">{{ quantity }}</text>
          <uni-icons type="plus-filled" size="24" color="#3db87f" @click="openSpecPopup"></uni-icons>
        </view>
        
        <view class="dish-header">
          <view class="dish-title-area">
            <view class="dish-name-container">
              <text class="dish-name">{{ dish.name }}</text>
              <view class="favorite-btn" @tap="toggleFavorite">
                <uni-icons :type="isFavorite ? 'heart-filled' : 'heart'" size="24" :color="isFavorite ? '#FF5252' : '#999999'"></uni-icons>
              </view>
            </view>
            <view class="dish-tags">
              <view class="dish-tag signature" v-if="dish.isSignature">招牌</view>
              <view class="dish-tag spicy" v-if="dish.spicyLevel">{{ dish.spicyLevel }}</view>
              <view class="dish-tag discount" v-if="dish.discount">{{ dish.discount }}</view>
            </view>
          </view>
        </view>
        
        <view class="dish-price-row">
          <text class="dish-price">¥{{ dish.price }}</text>
          <view class="dish-sales">月售 {{ dish.monthlySales || 0 }}</view>
        </view>
      </view>
      
      <!-- 菜品介绍卡片 -->
      <view class="desc-card">
        <view class="section-title">菜品介绍</view>
        <text class="dish-description">{{ dish.description }}</text>
      </view>
      
      <!-- 规格、辣度、口味信息卡片 -->
      <view class="ingredients-card">
        <view class="section-title">规格与口味</view>
        <view class="ingredients">
          <view class="ingredient-item">
            <text>规格: {{ dish.spec || '份' }}</text>
          </view>
          <view class="ingredient-item" v-if="dish.spicyLevel">
            <text>辣度: {{ dish.spicyLevel }}</text>
          </view>
          <view class="ingredient-item" v-if="dish.flavor">
            <text>口味: {{ dish.flavor || '标准' }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 规格选择弹出层 -->
    <spec-popup 
      ref="specPopupRef"
      :dish="dish"
      :initial-quantity="quantity"
      @confirm="handleSpecConfirm"
      @close="handleSpecClose"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import SpecPopup from '@/components/SpecPopup.vue';

// 获取页面参数
const dishId = ref(0);
const quantity = ref(0);
const isFavorite = ref(false);
const specPopupRef = ref<any>(null);

// 修改dish对象的类型定义
interface Dish {
  id: number;
  name: string;
  description: string;
  price: number;
  isSignature: boolean;
  discount: string;
  monthlySales: number;
  ingredients: string[];
  image: string;
  spicyLevel?: string; // 添加可选的辣度属性
  spec?: string;
  flavor?: string;
}

// 然后修改dish的ref定义
const dish = ref<Dish>({
  id: 1,
  name: '北京烤鸭',
  description: '北京烤鸭是具有世界声誉的北京著名菜式，起源于中国南北朝时期，是由中国汉族人创造的一种烤鸭方法，在当时是宫廷食品。用料为优质肉食鸭北京鸭，果木炭火烤制，色泽红润，肉质肥而不腻。',
  price: 198,
  isSignature: true,
  discount: '本周特惠',
  monthlySales: 238,
  ingredients: ['北京填鸭', '葱', '黄瓜', '甜面酱', '薄饼'],
  image: 'https://p9-bot-workflow-sign.byteimg.com/tos-cn-i-mdko3gqilj/31e44832a9c645df913ec4299773a51a.png~tplv-mdko3gqilj-image.png?rk3s=c8fe7ad5&x-expires=1773850158&x-signature=J52YknSQKiBo2bPtj6kedWUQkK8%3D'
});

onMounted(() => {
  try {
    const eventChannel = getOpenerEventChannel();
    eventChannel.on('dishDetail', (data: Dish) => {
      if (data) {
        dish.value = data;
        dishId.value = data.id;
        
        // 获取购物车中该菜品的数量
        const cartItems = uni.getStorageSync('cartItems') || [];
        const cartItem = cartItems.find((item: CartItem) => item.dishId === dishId.value);
        if (cartItem) {
          quantity.value = cartItem.quantity;
        }
      }
    });
  } catch (error) {
    console.error('初始化页面数据失败:', error);
    // 使用默认数据
  }
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 增加数量
const increaseQuantity = () => {
  quantity.value++;
  updateCart();
};

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 0) {
    quantity.value--;
    updateCart();
  }
};

// 打开规格选择弹窗
const openSpecPopup = () => {
  specPopupRef.value.open();
};

// 处理规格确认
const handleSpecConfirm = (data: any) => {
  // 更新购物车
  const cartItems = uni.getStorageSync('cartItems') || [];
  const index = cartItems.findIndex((item: CartItem) => 
    item.dishId === dishId.value && 
    item.spec === data.spec && 
    item.spicy === data.spicy && 
    item.flavor === data.flavor
  );
  
  if (index !== -1) {
    cartItems[index].quantity = data.quantity;
  } else {
    cartItems.push({
      dishId: dishId.value,
      quantity: data.quantity,
      spec: data.spec,
      spicy: data.spicy,
      flavor: data.flavor
    });
  }
  
  uni.setStorageSync('cartItems', cartItems);
  
  // 更新当前页面的数量显示
  quantity.value = data.quantity;
  
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
};

// 处理规格弹窗关闭
const handleSpecClose = () => {
  // 可以在这里处理弹窗关闭后的逻辑
};

// 添加到购物车
const addToCart = () => {
  if (quantity.value <= 0) {
    uni.showToast({
      title: '请先选择数量',
      icon: 'none'
    });
    return;
  }
  
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
  
  // 延迟返回
  setTimeout(() => {
    uni.navigateBack();
  }, 1500);
};

// 更新购物车
const updateCart = () => {
  const cartItems = uni.getStorageSync('cartItems') || [];
  const index = cartItems.findIndex((item: CartItem) => item.dishId === dishId.value);
  
  if (quantity.value > 0) {
    if (index !== -1) {
      cartItems[index].quantity = quantity.value;
    } else {
      cartItems.push({
        dishId: dishId.value,
        quantity: quantity.value
      });
    }
  } else if (index !== -1) {
    cartItems.splice(index, 1);
  }
  
  uni.setStorageSync('cartItems', cartItems);
};

// 获取上一页传递的数据
const getOpenerEventChannel = () => {
  try {
    // 在某些平台上可能不支持getOpenerEventChannel
    if ((uni as any).getOpenerEventChannel) {
      return (uni as any).getOpenerEventChannel();
    } else {
      console.warn('getOpenerEventChannel不可用，使用模拟数据');
      return {
        on: (eventName: string, callback: (data: Dish) => void) => {
          // 如果无法获取页面参数，使用默认数据
          if (eventName === 'dishDetail') {
            callback(dish.value);
          }
        }
      };
    }
  } catch (error) {
    console.error('获取eventChannel失败:', error);
    // 返回一个模拟的eventChannel
    return {
      on: (eventName: string, callback: (data: Dish) => void) => {
        // 如果无法获取页面参数，使用默认数据
        if (eventName === 'dishDetail') {
          callback(dish.value);
        }
      }
    };
  }
};

// 在script部分添加类型定义
interface CartItem {
  dishId: number;
  quantity: number;
  spec?: string;
  spicy?: string;
  flavor?: string;
}

// 切换收藏状态
const toggleFavorite = () => {
  isFavorite.value = !isFavorite.value;
  uni.showToast({
    title: isFavorite.value ? '已收藏' : '已取消',
    icon: 'none'
  });
};
</script>

<style lang="scss" scoped>

.container {
  min-height: 100vh;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
}

.status-bar {
  height: 44px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.back-button {
  position: fixed;
  top: 44px;
  left: 16px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.dish-image {
  width: 100%;
  height: 400rpx;
  object-fit: cover;
}

.content-area {
  flex: 1;
  padding: 20rpx;
  margin-top: -30rpx;
  position: relative;
  z-index: 10;
}

.info-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.quantity-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  z-index: 10;
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.dish-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
}

.dish-title-area {
  display: flex;
  flex-direction: column;
}

.dish-name-container {
  display: flex;
  align-items: flex-start;
  flex-direction: row;
  flex-wrap: nowrap;
  margin-bottom: 10rpx;
}

.favorite-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8rpx;
  margin-left: 20rpx;
  flex-shrink: 0;
}

.dish-name {
  font-size: 36rpx;
  font-weight: bold;
}

.dish-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin: 10rpx 0;
}

.dish-tag {
  display: inline-block;
  font-size: 20rpx;
  padding: 4rpx 10rpx;
  border-radius: 8rpx;
  width: auto;
  max-width: 120rpx;
  text-align: center;
}

.dish-tag.signature {
  background-color: #FFF8E1;
  color: #FFA000;
}

.dish-tag.spicy {
  background-color: #FFEBEE;
  color: #F44336;
}

.dish-tag.discount {
  background-color: #E8F5E9;
  color: #4CAF50;
}

.dish-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.dish-price {
  font-size: 36rpx;
  color: #3db87f;
  font-weight: bold;
  margin-right: 20rpx;
}

.dish-sales {
  font-size: 28rpx;
  color: #666;
}

.desc-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  margin: 30rpx 0 16rpx;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 24rpx;
  background-color: #3db87f;
  border-radius: 3rpx;
}

.dish-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.ingredients-card {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.ingredients {
  display: flex;
  flex-direction: column;
}

.ingredient-item {
  display: flex;
  justify-content: space-between;
  padding: 16rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.ingredient-item:last-child {
  border-bottom: none;
}

.quantity-text {
  font-size: 26rpx;
  min-width: 36rpx;
  text-align: center;
}

.add-to-cart-btn {
  background-color: vars.$primary-color;
  color: white;
}
</style> 